<template>
  <view class="address-container">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="nav-back" @tap="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <text class="nav-title">收货地址</text>
    </view>

    <!-- 地址列表 -->
    <scroll-view 
      scroll-y 
      class="address-scroll"
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      refresher-enabled
      :refresher-triggered="isRefreshing"
    >
      <!-- 加载中 -->
      <view v-if="loading" class="loading-container">
        <view class="spinner"></view>
        <text>加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else-if="addressList.length === 0" class="empty-container">
        <image src="/static/empty/address.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无收货地址</text>
      </view>

      <!-- 地址列表 -->
      <view v-else class="address-list">
        <view 
          v-for="item in addressList" 
          :key="item.id"
          class="address-item"
          @tap="handleSelect(item)"
        >
          <!-- 地址信息 -->
          <view class="address-info">
            <view class="user-info">
              <text class="name">{{item.receiverName}}</text>
              <text class="phone">{{formatPhone(item.receiverPhone)}}</text>
              <text v-if="item.isDefault" class="default-tag">默认</text>
            </view>
            <view class="address-detail">
              {{formatAddress(item)}}
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="address-actions">
            <view class="action-btn edit" @tap.stop="handleEdit(item)">
              <uni-icons type="compose" size="28" color="#666"></uni-icons>
              <text>编辑</text>
            </view>
            <view class="action-btn delete" @tap.stop="handleDelete(item)">
              <uni-icons type="trash" size="28" color="#ff4d4f"></uni-icons>
              <text>删除</text>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="bottom-button" @tap="handleAdd">
      <text class="button-text">新增收货地址</text>
    </view>
  </view>
</template>

<script>
import api from '@/config/api'
import { mapUviewIconName } from '@/utils/icon-mapper.js'

export default {
  data() {
    return {
      addressList: [],
      loading: true,
      isRefreshing: false,
      isFromOrder: false, // 是否从订单页面进入
      needRefresh: false
    }
  },

  onLoad(options) {
    this.isFromOrder = options.from === 'order'
    this.loadAddressList()
  },

  onShow() {
    // 如果需要刷新，重新加载地址列表
    if (this.needRefresh) {
      this.loadAddressList()
      this.needRefresh = false
    }
  },

  methods: {
    goBack() {
      uni.navigateBack()
    },

    async loadAddressList() {
      try {
        this.loading = true
        const res = await this.$api.user.address.list()
        if (res.code === 200) {
          this.addressList = res.data.map(item => ({
            id: item.id,
            receiverName: item.receiverName,
            receiverPhone: item.receiverPhone,
            province: item.province,
            city: item.city,
            district: item.district,
            detailAddress: item.detailAddress,
            postCode: item.postCode,
            label: item.label || '家',
            isDefault: item.isDefault === 1,
            fullAddress: `${item.province}${item.city}${item.district}${item.detailAddress}`
          }))
        }
      } catch (error) {
        console.error('加载地址列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        if (this.isRefreshing) {
          uni.stopPullDownRefresh()
          this.isRefreshing = false
        }
      }
    },

    async onRefresh() {
      this.isRefreshing = true
      await this.loadAddressList()
    },

    formatPhone(phone) {
      if (!phone) return ''
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    },

    formatAddress(item) {
      return `${item.province}${item.city}${item.district}${item.detailAddress}`
    },

    handleSelect(item) {
      if (!this.isFromOrder) return
      
      const pages = getCurrentPages()
      const prevPage = pages[pages.length - 2]
      if (prevPage) {
        prevPage.$vm.updateAddress(item)
        uni.navigateBack()
      }
    },

    handleAdd() {
      uni.navigateTo({
        url: '/pages/user/address/add'
      })
    },

    handleEdit(item) {
      uni.navigateTo({
        url: `/pages/user/address/edit?id=${item.id}`
      })
    },

    async handleDelete(item) {
      try {
        await uni.showModal({
          title: '提示',
          content: '确定要删除该地址吗？',
          success: async (res) => {
            if (res.confirm) {
              await this.deleteAddress(item.id)
            }
          }
        })
      } catch (error) {
        console.error('删除地址失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    },

    async handleSetDefault(item) {
      try {
        await this.setDefault(item.id)
      } catch (error) {
        console.error('设置默认地址失败:', error)
        uni.showToast({
          title: '设置失败',
          icon: 'none'
        })
      }
    },
    
    loadMore() {
      // 这里实现加载更多的逻辑，如果需要的话
      console.log('加载更多地址')
    },

    async setDefault(id) {
      try {
        await this.$api.user.address.setDefault(id)
        await this.loadAddressList()
        uni.showToast({
          title: '设置成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('设置默认地址失败:', error)
        uni.showToast({
          title: '设置失败',
          icon: 'none'
        })
      }
    },

    async deleteAddress(id) {
      try {
        await this.$api.user.address.delete(id)
        await this.loadAddressList()
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('删除地址失败:', error)
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.address-container {
  min-height: 100vh;
  background: #f8f8f8;
  position: relative;
}

.nav-bar {
  height: 88rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  position: relative;
  
  .nav-back {
    font-size: 36rpx;
    color: #333;
    padding: 20rpx;
    margin-left: -20rpx;
  }
  
  .nav-title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }
}

.address-scroll {
  height: calc(100vh - 180rpx);
  padding: 20rpx;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
  
  .spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #ff5500;
    border-radius: 50%;
    animation: spinner 1s linear infinite;
    margin-bottom: 20rpx;
  }
  
  text {
    font-size: 28rpx;
    color: #666;
  }
}

@keyframes spinner {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.address-list {
  .address-item {
    background: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
    
    .address-info {
      .user-info {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;
        
        .name {
          font-size: 32rpx;
          font-weight: 500;
          color: #333;
          margin-right: 20rpx;
        }
        
        .phone {
          font-size: 28rpx;
          color: #666;
          margin-right: 20rpx;
        }
        
        .default-tag {
          font-size: 24rpx;
          color: #ff5500;
          background: rgba(255, 85, 0, 0.1);
          padding: 2rpx 8rpx;
          border-radius: 4rpx;
        }
      }
      
      .address-detail {
        font-size: 28rpx;
        color: #666;
        line-height: 1.5;
      }
    }
    
    .address-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 20rpx;
      padding-top: 20rpx;
      border-top: 1rpx solid #eee;
      
      .action-btn {
        display: flex;
        align-items: center;
        margin-left: 30rpx;
        
        text {
          font-size: 28rpx;
          color: #666;
          margin-left: 8rpx;
        }
        
        &.delete text {
          color: #ff4d4f;
        }
      }
    }
  }
}

.bottom-button {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100rpx;
  background: #ff5500;
  display: flex;
  justify-content: center;
  align-items: center;
  
  .button-text {
    font-size: 32rpx;
    color: #fff;
  }
}
</style> 